<template>
  <view class="container channel_info">
    <view class="zs_section_title">基础信息</view>
    <tm-sheet :margin="[24, 20]" :round="3" :shadow="2">
      <view class="cus_item">
        <view class="cus_item_label">渠道类型</view>
        <view class="cus_item_value">{{ renderField(channelType, channelInfo.type)}}</view>
      </view>
      <view class="cus_item">
        <view class="cus_item_label">主体</view>
        <view class="cus_item_value">{{renderField(entityOptions, channelInfo.entity)}}</view>
      </view>
      <view class="cus_item">
        <view class="cus_item_label">渠道方</view>
        <view class="cus_item_value">{{channelInfo.name}}</view>
      </view>
      <view class="cus_item">
        <view class="cus_item_label">收款账户</view>
        <view class="cus_item_value">{{channelInfo.bank_account_name}}</view>
      </view>
      <view class="cus_item">
        <view class="cus_item_label">开户行</view>
        <view class="cus_item_value">{{channelInfo.bank_name}}</view>
      </view>
      <view class="cus_item">
        <view class="cus_item_label">银行账号</view>
        <view class="cus_item_value">{{channelInfo.bank_account}}</view>
      </view>
      <view class="cus_item">
<!--         少字段 todo-->
        <view class="cus_item_label">纳税人识别号</view>
<!--        <view class="cus_item_value">{{channelInfo.rate}}</view>-->
      </view>
      <view class="cus_item">
        <view class="cus_item_label">通讯地址</view>
        <view class="cus_item_value">{{channelInfo.address}}</view>
      </view>
      <view class="cus_item">
        <view class="cus_item_label">备注</view>
        <view class="cus_item_value">{{channelInfo.remark}}</view>
      </view>
    </tm-sheet>
    <view class="zs_section_title">介绍客户列表</view>
    <u-tabs :list="tabsTitle" @change="tabschange" :current="activeKey" lineColor="#4A76F7" :inactiveStyle="{color: '#8091A4', fontSize: '28rpx'}" :activeStyle="{ color: '#333333', fontWeight: '500'}"></u-tabs>

    <view class="client_list">
      <tm-sheet :margin="[24, 20]" :round="3" :shadow="2">
        <view class="turnover_num">
          <view class="turnover_num_text">
            <tm-icon fontSize="24" name="iconfont icon-fangyuantubiao" color="#4A76F7" @click="openFilter" ></tm-icon>
            <text style="padding-left: 4px;">成交率</text>
          </view>
          <view class="turnover_num_value">
            <text class="turnover_rate">{{channelInfo.rate || 0}}</text>
            <text class="turnover_symbol">%</text>
          </view>
        </view>
      </tm-sheet>
      <view v-if="introduceClients.length > 0" v-for="item in introduceClients" :key="item.id">
        <tm-sheet :margin="[24, 20]" :round="3" :shadow="2">
          <view class="channel_item_title">
            <view class="channel_type">
              <!--            "status": 1 //状态：1=待跟进，2=未上门，3=已上门，4=已签约，5=已流失-->
              <text v-if="item.status === 1" style="color: #165DFF">待跟近</text>
              <text v-if="item.status === 2" style="color: #F5319D">未上门</text>
              <text v-if="item.status === 3" style="color: #2ACFCE">已上门</text>
              <text v-if="item.status === 4" style="color: #00B42A">已签约</text>
            </view>
            <view v-if="item.follow_at" class="sign_time">
              <text class="sign_text">最近跟近</text>
              <text class="sign_time_text">{{moment(item.follow_at).format('YYYY-MM-DD')}}</text>
            </view>
          </view>
          <view class="channel_item_head">
            <view class="channel_item_type">
              <image src="@/static/img/client_header.png"></image>
            </view>
            <view class="channel_head_inner">
              <view>
                <view class="inner_value"><text class="inner_value_name">{{ item.follow_name }}</text><text class="inner_value_type">{{item.follow_user ? '跟进人': ''}}</text></view>
                <view class="inner_text">{{item.mobile}}</view>
              </view>
              <view class="inner_phone">
                <tm-icon fontSize="36" name="iconfont icon-lianxi" color="#4A76F7" ></tm-icon>
                <view class="inner_phone_text">联系</view>
              </view>
            </view>
          </view>
          <view class="cus_item">
            <view class="cus_item_label">客户名称</view>
            <view class="cus_item_value">{{item.name}}</view>
          </view>
          <view class="cus_item">
            <view class="cus_item_label">行业</view>
            <view class="cus_item_value">{{item.industry_text}}</view>
          </view>
          <view class="cus_item">
            <view class="cus_item_label">预租面积</view>
            <view class="cus_item_value">{{item.pre_lease_area_min + '-' + item.pre_lease_area_max}}</view>
          </view>
          <view class="cus_item">
            <view class="cus_item_label">预算价格</view>
            <view class="cus_item_value">{{item.per_lease_price}}</view>
          </view>
        </tm-sheet>
      </view>
      <view v-else>
        <defaultGraph></defaultGraph>
      </view>
    </view>
    <view class="cus_footer_btn">
      <view class="operate_btns">
        <tm-button block label="渠道联系人" round="25"  @click="gotoChannelLinkman"></tm-button>
        <view class="icon_btns">
          <view class="footer_edits" @click="editChannel" >
            <tm-icon fontSize="24" name="iconfont icon-chakanfapiao1" color="#8091A4"></tm-icon>
            <view class="operate_label">编辑</view>
          </view>
          <view class="footer_edits" @click="deleteChannel">
            <tm-icon fontSize="24" name="iconfont icon-shanchu" color="#8091A4" ></tm-icon>
            <view class="operate_label">删除</view>
          </view>
        </view>
      </view>
    </view>

<!--     渠道联系人列表  -->
    <u-popup :show="linkmanVisible" ref="linkmanRef" :round="10">
      <view class="contact_header">
        <view class="header_text">
          {{!addLinkmanVisible ? `渠道联系人（${contactNums}）` : form.id ? '编辑渠道联系人' : '添加渠道联系人'}}
        </view>
        <view class="close_icon" @click="closePopup">
          <tm-icon fontSize="24" name="iconfont icon-danchuangguanbi" color="#3D3D3D"></tm-icon>
        </view>
      </view>
      <view v-if="!addLinkmanVisible" class="linkman_content">
        <view v-if="contactList.length > 0" v-for="item in contactList" :key="item.id" class="linkman_item">
          <tm-sheet :margin="[24, 20]" :round="3" :shadow="2" color="#FAFAFA">
          <view class="linkman_top">
            <view class="channel_item_type">
              <image src="@/static/img/client_header.png"></image>
            </view>
            <view class="linkman_info">
              <view class="info_top">
                <text class="info_name">{{ item.name }}</text>
                <text class="operate_label">{{item.mobile}}</text>
              </view>
              <view class="info_bottom">
                <view class="info_email">
                  <text class="operate_label">邮箱：</text>
                  <text class="email_value">{{item.email}}</text>
                  <text class="email_copy_text" @click="() => copyEmail(item.email)">复制</text>
                </view>
              </view>
            </view>

          </view>
          <view class="linkman_bottom">
            <view class="linkman_phone" @click="() => callPhone(item.mobile)">
              <tm-icon fontSize="24" name="iconfont icon-bodadianhua" color="#165DFF"></tm-icon>
              <text class="phone_text">拨打电话</text>
            </view>
            <view class="icon_btns">
              <view class="footer_edits" @click="() => editLinkman(item)">
                <tm-icon fontSize="24" name="iconfont icon-chakanfapiao1" color="#8091A4"></tm-icon>
                <view class="operate_label">编辑</view>
              </view>
              <view class="footer_edits" @click="() => deleteLinkman(item)">
                <tm-icon fontSize="24" name="iconfont icon-shanchu" color="#8091A4"></tm-icon>
                <view class="operate_label">删除</view>
              </view>
            </view>
          </view>
          </tm-sheet>
        </view>
        <view v-else>
          <defaultGraph></defaultGraph>
        </view>
        <view class="linkman_btns">
          <tm-button block label="添加渠道联系人" round="25"  @click="addChannelContact"></tm-button>
        </view>
      </view>
<!--       添加 渠道联系人 -->
      <view v-else class="contact_info">
        <view class="zs_form_item">
          <view class="zs_form_item_label"><text class="zs_form_required">*</text>联系人姓名</view>
          <view class="zs_form_item_value">
            <up-input
                placeholder="请输入"
                border="surround"
                v-model="form.name"
                placeholderStyle="color: #999"
                customStyle="background: #F9F9F9"
            ></up-input>
          </view>
        </view>
        <view class="zs_form_item">
          <view class="zs_form_item_label"><text class="zs_form_required">*</text>联系人电话</view>
          <view class="zs_form_item_value">
            <up-input
                placeholder="请输入"
                border="surround"
                placeholderStyle="color: #999"
                v-model="form.mobile"
                customStyle="background: #F9F9F9"
            ></up-input>
          </view>
        </view>
        <view class="zs_form_item">
          <view class="zs_form_item_label">邮箱</view>
          <view class="zs_form_item_value">
            <up-input
                placeholder="请输入"
                border="surround"
                v-model="form.email"
                placeholderStyle="color: #999"
                customStyle="background: #F9F9F9"
            ></up-input>
          </view>
        </view>
        <view class="zs_form_item">
          <view class="zs_form_item_label">对接人</view>
          <view class="zs_form_item_value">
            <view @click="() => userVisible = true" class="zs_form_select">
              <view v-if="form.follow_name">{{form.follow_name}}</view>
              <view v-else style="color: #999999;">请选择</view>
              <tm-icon fontSize="24" name="iconfont icon-youjiantou" color="#3A6CB1"></tm-icon>
            </view>

          </view>
        </view>
        <view class="linkman_btns">
          <tm-button block label="提交" round="25"  @click="saveChannleContact"></tm-button>
        </view>
      </view>
    </u-popup>

<!--    对接人滑框-->
    <u-picker :show="userVisible" :columns="buttList" keyName="label" @confirm="selectButtUser"></u-picker>

<!--     删除提示 -->
    <tm-modal
        color="white"
        okColor="#fff"
        border="3"
        title="提示"
        v-model:show="tipData.visible"
        titleStyle="[{font-size: 18px;}]"
        zIndex="999999"
    >
      <template #default>
        <view class="content_text" style="text-align: center;padding-top: 20px;">{{tipData.content}}</view>
      </template>
      <template #button>
        <view class="modal_bottom_btn">
          <view class="modal_footer_btn modal_cancel_btn" @click="cancel">暂不</view>
          <view class="modal_footer_btn modal_sure_btn" @click="confirmDelete">确认</view>
        </view>
      </template>
    </tm-modal>
  </view>
</template>
<script setup lang="ts">

import {ref} from "vue";
import { channelDetail, introduceClientList, channelContactList, channelCustomerStatus, getZsUserList, updateChannelContact, createChannelContact, deleteChannelInfo, channelUserStatic,deleteChannelContact } from '@/api_request/api'
import { onLoad } from '@dcloudio/uni-app'
import { entityOptions, channelType } from '@/utils/dictionary'
import {cloneDeep, each} from 'lodash'
import {matchDictionaryName, validateEmail, validateNumber} from "@/utils/utils";

const tabsTitle = ref([
  {
    name: '全部',
    badge: {
      value: 0,
    },
  },
  {
    name: '未上门',
    type: 2,
    badge: {
      value: 0,
    }
  },
  {
    name: '已上门',
    type: 3,
    badge: {
      value: 0,
    }
  },
  {
    name: '已签约',
    type: 4,
    badge: {
      value: 0,
    }
  }
])
const activeKey = ref(0)

const userVisible = ref<Boolean>(false)
const linkmanVisible = ref<Boolean>(false)
const linkmanRef = ref<any>(null)
// 渠道联系人
const contactList = ref<any>([])
const addLinkmanVisible = ref<Boolean>(false)
const introduceClients = ref<any>([])

const form = ref<any>({})
const rules = ref<any>({

})
const tipData = ref<any>({
  visible: false,
  title: '',
  content: '',
  type: 0, // 1 渠道   2 渠道联系人
  rowData: {} // 当前确认的数据
})
const buttList = ref<any[]>([])
const channelInfo = ref<any>({})
const tabschange = (item) => {
  console.log('jp======item',item)
  getIndustClients({channel_id: channelInfo.value.id, status: item.type})
}
const renderField = (dataArr, value) => {
  return matchDictionaryName(dataArr, value)
}



const getChannelDetail = (data) =>{
  channelDetail(data).then(res => {
    console.log('jp======渠道详情',res)
    channelInfo.value = res.data
  })
}
// 介绍客户列表
const getIndustClients = (data) => {
  introduceClientList(data).then(res =>{
    console.log('jp======介绍客户列表',res)
    introduceClients.value = res.data.list
  })
}
// 编辑渠道
const editChannel = () => {
  uni.navigateTo({url: `/subpkg/create_channel/index?id=${channelInfo.value.id}`})
}
// 删除渠道
const deleteChannel = () => {
  console.log('jp======输惨胡渠道',)
  tipData.value.visible= true
  tipData.value.title= '提示'
  tipData.value.content='确定删除该渠道吗'
  tipData.value.type = 1
  // tipData.value.rowData= {} // 当前确认的数据
}


// 渠道联系人
const contactNums = ref<number>(0)
const getChannelLinkMan = (id?) => {
  channelContactList({channel_id: id || channelInfo.value.id, page_num: 1, page_size: 500}).then(res => {
    console.log('jp=======渠道联系人列表',res)
    contactList.value = res.data?.list
    contactNums.value = res.data?.total
  })
}

const gotoChannelLinkman = () => {
  linkmanVisible.value = true
}

const closePopup = () => {
  if(!addLinkmanVisible.value) {
    console.log('jp======linkmanRef.value',linkmanRef.value)
    linkmanVisible.value = false
    linkmanRef.value.close()
    return
  }
  addLinkmanVisible.value = false

}
const open = () => {
  console.log('jp=======带卡',)
}

const selectButtUser = (val) => {
  console.log('jp=======选择对接人',val)
  const row = val.value[0]
  form.value.person = row.id
  form.value.follow_name = row.label
  userVisible.value = false
}

// 保存渠道联系人
const saveChannleContact = async () => {
  if(!form.value.name) return uni.$showMsg('请输入联系人名称')
  if(!form.value.mobile || (form.value.mobile && !validateNumber(form.value.mobile))) return uni.$showMsg('请输入正确的手机号')
  const params = {
    ...form.value
  }
  console.log('jp======params',params)
  let res: any
  if(params.id) {
    res = await updateChannelContact(params)
  } else {
    params.channel_id = channelInfo.value.id
    res = await createChannelContact(params)
  }
  if(res.code === 200){
    uni.$showMsg('操作成功！')
    getChannelLinkMan()
    // 关闭联系人弹框  todo
    addLinkmanVisible.value = false
    return
  }
  uni.$showMsg(res.message)
}
// 当前编辑的渠道联系人--存储
const curEditChannelLinkman = ref<any>({})

// 添加渠道联系人 todo
const addChannelContact = () => {
  addLinkmanVisible.value = true
  form.value = {}
}


const editLinkman = (item) => {
  addLinkmanVisible.value = true
  curEditChannelLinkman.value = item
  form.value = cloneDeep(item)
}


const deleteLinkman = async (item) => {
  tipData.value.visible = true
  tipData.value.title = '提示'
  tipData.value.content = '确定删除该联系人吗？'
  tipData.value.rowData = item
  tipData.value.type = 2
}

const cancel = () => {
  tipData.value.visible = false
  tipData.value.title = ''
  tipData.value.content = ''
  tipData.value.rowData = {}
  tipData.value.type = 0
}
const confirmDelete = async () => {
  console.log('jp=======确认删除',)
  // 判断删除渠道还是渠道联系人
  let res: any
  if(tipData.value.type === 1) {
  //   删除渠道
    res = await deleteChannelInfo({id: channelInfo.value.id})
    uni.navigateTo({url: `/subpkg/channel_list/index`})
  } else if(tipData.value.type === 2) {
  //  删除渠道联系人
    const row = tipData.value.rowData
    res = await deleteChannelContact({id: row.id})
  }

  tipData.value.visible = false
  tipData.value.title = ''
  tipData.value.content = ''
  tipData.value.rowData = {}
  if(res.code === 200 ) {
    uni.$showMsg('删除成功！')
    // 刷新列表
    if(tipData.value.type === 1){
    // 返回渠道列表页面
      uni.navigateTo({url: `/subpkg/channel_list/index`})
    } else if(tipData.value.type === 2) {
      getChannelLinkMan()
      addLinkmanVisible.value = false
    }
    return
  }
  uni.$showMsg(res.message)
}

const callPhone = (value) => {
  uni.makePhoneCall({
    phoneNumber: value
  });
}
const copyEmail = (value) => {
  wx.setClipboardData({ //设置系统剪贴板的内容
    data: value,
    success(res) {
      console.log(res, value);
      wx.getClipboardData({ // 获取系统剪贴板的内容
        success(res) {
          uni.$showMsg('邮箱复制成功！')
        }
      })
    }
  })
}
onLoad((option: any) => {
  console.log('jp======options',option)
  const channel_id= option.id
  // 渠道详情
  getChannelDetail({id: option.id})
  // 介绍客户
  getIndustClients({channel_id})
  getChannelLinkMan(channel_id)
  // 渠道下客户状态统计
  channelCustomerStatus({channel_id }).then(res => {
    console.log('jp=======客户状态统计',res)
    const __tabsTitle = [...tabsTitle.value]
    each(res.data, (item) => {
      const index = __tabsTitle.findIndex(v => v.type === item.type)
      if(index !== -1) {
        __tabsTitle[index].badge.value = item.count
      }
    })
    tabsTitle.value = __tabsTitle
  })

//  对接人
  getZsUserList({}).then(res => {
    console.log('jp=======对接人',res)
    const __buttList:any[] = []
    for(const i in res.data) {
      __buttList.push({
        id: i,
        label: res.data[i]
      })
    }
    console.log('jp=======__buttList',__buttList)
    buttList.value = [__buttList]
  })
})
</script>
<style lang="scss" scoped>
.channel_info{
  .channel_item_type{
    background: none;
    image{
      width: 50px;
      height:50px;
    }
  }
  .channel_head_inner{
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-width: 0;
    width: 100%;
    .inner_phone_text{
      color: $cus-color-1;
    }
  }
  .inner_value_name{
    color: #333;
  }
  .inner_value_type{
    font-size: $cus-font-size-12;
    padding-left: 10px;
  }
  .inner_text{
    color: $cus-color-1;
  }
  .turnover_num{
    display: flex;
    justify-content: space-between;
    .turnover_num_text{
      display: flex;
      align-items: center;
    }
    .turnover_rate{
      font-size: 20px;
      color: $cus-bg-color;
    }
    .turnover_symbol{
      color: $cus-color-1;
      font-size: $cus-font-size-12;
    }
  }

  .operate_label{
    color: $cus-color-1;
    font-size: $cus-font-size-12;
  }
  .operate_btns{
    position: relative;
    padding-right: 100px;
    .icon_btns{
      position: absolute;
      top: 8px;
      right: 10px;
      display: flex;
      width: 70px;
      justify-content: space-between;
      .operate_label{
        padding-top: 2px;
      }
    }
  }

  //渠道联系人列表
  .contact_header{
    border-bottom: 1px solid #D8D8D8;
    padding: 18px 0;
    text-align: center;
    position: relative;
    .close_icon{
      position: absolute;
      top: 24px;
      right: 20px;
    }
    .header_text{
      font-size: $cus-font-size-18;
    }
  }
  .linkman_item{

  }
  .linkman_top{
    display: flex;
    align-items: center;
    .linkman_info{
      padding-left: 10px;
      .info_bottom{
        padding-top: 10px;
      }
    }
    .phone_text{
      color: $cus-bg-color;
    }
  }
  .linkman_bottom{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: 26px;
    .linkman_phone{

    }
    .linkman_phone{
      display: flex;
      align-items: center;
      .phone_text{
        color: $cus-color-8;
        padding-left: 8px;
      }
    }
    .icon_btns{
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100px;
    }
  }
  .info_name{
    padding-right: 10px;
  }
  .email_value{
    padding: 0 10px;
  }
  .email_copy_text{
    color: $cus-bg-color;
  }
  .contact_info{
    padding: 20px;

  }
  .linkman_btns{
    padding-top: 20px;
  }
}
</style>